const service = require('../myAddressService.js');
const utilService = require('../../../../utils/utilService.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: "",
    phone: "",
    address: "",
    zipCode: "",
    regions: ['地区信息'],
    province: "",//省
    city: "",//城市
    area: "",//区县
    chooseType: 1, //1选择地址  2定位
    country: "",//国家 
    street: "",//街道
    street_number: "",
    addressId: "",
    isDefault: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.jsonStr != null) {
      var data = JSON.parse(options.jsonStr);

      this.setData({
        name: data.name,
        phone: data.phone,
        address: data.address,
        zipCode: data.zipCode,
        regions: [data.province, data.city, data.area],
        addressId: data.id,
        province: data.province,//省
        city: data.city,//城市
        area: data.area,//区县
        country: data.country,
        isDefault: (data.defaultFlag == 0 ? true : false)
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  bindRegionChange: function (e) {
    var array = e.detail.value
    this.setData({
      regions: e.detail.value,
      province: array[0],
      city: array[1],
      area: array[2],
      chooseType: 1,
    })
  },

  chooseLocation: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        var data = {
          location: res.latitude + "," + res.longitude,
          //腾讯底图key BGIBZ-BJA3W-PKYR7-R5GND-5RHJS-XZF7Z
          key: "BGIBZ-BJA3W-PKYR7-R5GND-5RHJS-XZF7Z"
        };
        that.decodeLocationByTX(res, data);
      },
      fail: function (error) {
        console.log(error)
        if (error.errMsg.indexOf("auth") != -1) {
          that.authorizationLocation()
        }
      }
    })
  },
  /**
   * 逆向解析地址
   */
  //腾讯
  decodeLocationByTX: function (res, data) {
    var that = this;
    wx.request({
      url: "https://apis.map.qq.com/ws/geocoder/v1/",
      data: data,
      method: "GET",
      success: function (result) {
        console.log(result.data.result.address_component);
        var resion = result.data.result.address_component
        if (resion) {
          that.setData({
            regions: [resion.province, resion.city, resion.district],
            address: res.address + res.name,
            chooseType: 2,
            province: resion.province,
            city: resion.city,
            area: resion.district,
            country: resion.nation,
            street_number: resion.street_number,
            street: resion.street,
          })
        }
      },
      fail: function (res) {
        console.log(res);
        typeof fail == "function" && fail(res);
      }
    });
  },

  switchChange: function (e) {
    this.setData({ isDefault: e.detail.value })
    service.chooseAddress(this.data.addressId,
      function (result) {
        wx.hideLoading()
        wx.showToast({
          title: '默认地址设置成功',
          icon: 'success',
          duration: 2000
        })
      },
      function (error) {
        wx.hideLoading()
        wx.showToast({
          title: '默认地址设置失败',
          icon: 'none',
          duration: 2000,
        })
      })
  },

  authorizationLocation: function () {
    wx.openSetting({
      success: (res) => {

      }
    })
  },

  nameInput: function (e) {
    this.setData({
      name: e.detail.value
    })
  },

  phoneInput: function (e) {
    this.setData({
      phone: e.detail.value
    })
  },

  addressInput: function (e) {
    this.setData({
      address: e.detail.value
    })
  },

  zipCodeInput: function (e) {
    this.setData({
      zipCode: e.detail.value
    })
  },

  finsh: function () {
    var msg = ""
    if (this.data.zipCode == null || this.data.zipCode.length <= 0) {
      msg = "请填写邮政编码！"
    }
    if (this.data.address == null || this.data.address.length <= 0) {
      msg = "请填写详细地址！"
    }
    if (this.data.regions == null || this.data.regions.length < 3) {
      msg = "请填写收件地区！"
    }
    if (this.data.phone == null || this.data.phone.length <= 0) {
      msg = "请填手机号码！"
    }
    if (this.data.name == null || this.data.name.length <= 0) {
      msg = "请填写联系人！"
    }

    if (msg != "") {
      wx.showToast({
        title: msg,
        icon: 'none',
        duration: 2000
      })
      return
    } else {
      this.request()
    }
  },

  request: function () {
    var param = {
      "userId": getApp().globalData.userId,
      "name": this.data.name,
      "phone": this.data.phone,
      "region": this.data.regions[0] + this.data.regions[1] + this.data.regions[2],
      "address": this.data.address,
      "zipCode": this.data.zipCode,
      "province": this.data.province,
      "city": this.data.city,
      "area": this.data.area,
      "chooseType": this.data.chooseType,
      "street": this.data.street,
      "street_number": this.data.street_number,
      "country": this.data.country,
      "flag": (this.data.isDefault == true ? 0 : 1)
    }
    if (this.data.addressId != null) {
      param.addressId = this.data.addressId
    }
    wx.showLoading({
      title: '请稍等',
    })
    var that = this
    service.requestAdd(param,
      function (data) {
        wx.hideLoading()
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 1000,
          complete: function () {

          }
        })
        setTimeout(function () {
          that.configResult()
        }, 1000)
      })
  },

  configResult: function () {
    var pages = getCurrentPages()
    var prePage = pages[pages.length - 2]
    prePage.reload()

    wx.navigateBack({
      delta: 1
    })
  }
})